import es
import popuplib 
import sqlite3

# Get the paths for the sqlite database.
addonPath = es.ServerVar('eventscripts_addondir')
playersDBpath = addonPath + '\pvkii_shop\players.sqlite'

conn = sqlite3.connect(playersDBpath)
c = conn.cursor()

def load():
    c.execute("CREATE TABLE IF NOT EXISTS 'players' ('steamid' TEXT PRIMARY KEY  NOT NULL , 'coins' INTEGER NOT NULL  DEFAULT 0, 'rate' INTEGER NOT NULL  DEFAULT 10)")
    conn.commit()
    
    es.regsaycmd('/shop', 'pvkii_shop/sendPopup', 'Shows Shop Popup')

def unload():
    es.unregsaycmd('/shop')

def es_player_validated(ev):
    c.execute("SELECT COUNT(*) from players where steamid = ?", (ev['networkid'],))
    check = c.fetchone()
   
    if (check[0] == 0):
        c.execute("INSERT INTO players (steamid) VALUES (?)", (ev['networkid'],))
        conn.commit()

def player_death(ev):
    c.execute("UPDATE players SET coins = coins + rate WHERE steamid = ?" , (ev['es_attackersteamid'],))
    conn.commit()

def sendPopup():
    user = es.getcmduserid()
    steamid = es.getplayersteamid(user)
    
    c.execute("SELECT coins FROM players WHERE steamid = ?", (steamid,))
    coins = c.fetchone()
        
    coinPopup = popuplib.create('coinPopup')
    coinPopup.addline('PVKII Shop Menu')
    coinPopup.addline('-----------------')
    coinPopup.addline(' ')
    coinPopup.addline('Coins: %s' % (coins[0]))
    
    coinPopup.send(user)